//
//  UnitConverterViewController.m
//  SnapCAD
//
//  Created by 暗流澎涌 on 2025/7/25.
//

#import "UnitConverterViewController.h"

@interface UnitConverterViewController () <UIPickerViewDataSource, UIPickerViewDelegate>

// UI Components
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;

// Category Tabs
@property (nonatomic, strong) UIView *tabsContainer;
@property (nonatomic, strong) NSArray<UIButton *> *categoryButtons;
@property (nonatomic, assign) NSInteger selectedCategoryIndex;

// Converter Interface
@property (nonatomic, strong) UIView *fromContainer;
@property (nonatomic, strong) UITextField *fromTextField;
@property (nonatomic, strong) UIButton *fromUnitButton;
@property (nonatomic, strong) UIButton *swapButton;
@property (nonatomic, strong) UIView *toContainer;
@property (nonatomic, strong) UITextField *toTextField;
@property (nonatomic, strong) UIButton *toUnitButton;

// Quick Conversions
@property (nonatomic, strong) UIView *quickConversionsContainer;
@property (nonatomic, strong) UILabel *quickConversionsTitle;
@property (nonatomic, strong) UIStackView *quickConversionsStack;

// Data
@property (nonatomic, strong) NSArray<NSString *> *categories;
@property (nonatomic, strong) NSDictionary<NSString *, NSArray<NSString *> *> *units;
@property (nonatomic, strong) NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *conversionFactors;
@property (nonatomic, assign) NSInteger fromUnitIndex;
@property (nonatomic, assign) NSInteger toUnitIndex;

@end

@implementation UnitConverterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupData];
    [self setupUI];
    [self updateConversion];
}

- (void)setupData {
    self.categories = @[@"Length", @"Area", @"Volume", @"Angle"];
    
    self.units = @{
        @"Length": @[@"Meters", @"Feet", @"Inches", @"Millimeters", @"Centimeters", @"Kilometers"],
        @"Area": @[@"Square Meters", @"Square Feet", @"Square Inches", @"Hectares", @"Acres"],
        @"Volume": @[@"Cubic Meters", @"Cubic Feet", @"Liters", @"Gallons", @"Cubic Inches"],
        @"Angle": @[@"Degrees", @"Radians", @"Gradians"]
    };
    
    // 转换因子（以第一个单位为基准）
    self.conversionFactors = @{
        @"Length": @{
            @"Meters": @1.0,
            @"Feet": @3.28084,
            @"Inches": @39.3701,
            @"Millimeters": @1000.0,
            @"Centimeters": @100.0,
            @"Kilometers": @0.001
        },
        @"Area": @{
            @"Square Meters": @1.0,
            @"Square Feet": @10.7639,
            @"Square Inches": @1550.0,
            @"Hectares": @0.0001,
            @"Acres": @0.000247105
        },
        @"Volume": @{
            @"Cubic Meters": @1.0,
            @"Cubic Feet": @35.3147,
            @"Liters": @1000.0,
            @"Gallons": @264.172,
            @"Cubic Inches": @61023.7
        },
        @"Angle": @{
            @"Degrees": @1.0,
            @"Radians": @0.0174533,
            @"Gradians": @1.11111
        }
    };
    
    self.selectedCategoryIndex = 0;
    self.fromUnitIndex = 0;
    self.toUnitIndex = 1;
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0]; // gray-50
    
    // Scroll View
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];
    
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
    
    [self setupHeader];
    [self setupCategoryTabs];
    [self setupConverterInterface];
    [self setupQuickConversions];
    [self setupConstraints];
}

- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.headerView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.headerView.layer.shadowOffset = CGSizeMake(0, 1);
    self.headerView.layer.shadowOpacity = 0.1;
    self.headerView.layer.shadowRadius = 2;
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.headerView];
    
    // Back Button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    UIImage *backImage = [UIImage systemImageNamed:@"arrow.left"];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    self.backButton.tintColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.backButton];
    
    // Title Label
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Unit Converter";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.titleLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.11 alpha:1.0];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];
}

- (void)setupCategoryTabs {
    self.tabsContainer = [[UIView alloc] init];
    self.tabsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.tabsContainer];
    
    NSMutableArray *buttons = [NSMutableArray array];
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.distribution = UIStackViewDistributionFillEqually;
    stackView.spacing = 8;
    stackView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tabsContainer addSubview:stackView];
    
    for (NSInteger i = 0; i < self.categories.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitle:self.categories[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        button.layer.cornerRadius = 8;
        button.tag = i;
        [button addTarget:self action:@selector(categoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [buttons addObject:button];
        [stackView addArrangedSubview:button];
    }
    
    self.categoryButtons = [buttons copy];
    [self updateCategoryButtons];
    
    [NSLayoutConstraint activateConstraints:@[
        [stackView.topAnchor constraintEqualToAnchor:self.tabsContainer.topAnchor],
        [stackView.leadingAnchor constraintEqualToAnchor:self.tabsContainer.leadingAnchor],
        [stackView.trailingAnchor constraintEqualToAnchor:self.tabsContainer.trailingAnchor],
        [stackView.bottomAnchor constraintEqualToAnchor:self.tabsContainer.bottomAnchor],
        [stackView.heightAnchor constraintEqualToConstant:40]
    ]];
}

- (void)setupConverterInterface {
    // From Container
    [self setupFromContainer];
    
    // Swap Button
    [self setupSwapButton];
    
    // To Container
    [self setupToContainer];
}

- (void)setupFromContainer {
    self.fromContainer = [[UIView alloc] init];
    self.fromContainer.backgroundColor = [UIColor whiteColor];
    self.fromContainer.layer.cornerRadius = 12;
    self.fromContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    self.fromContainer.layer.shadowOffset = CGSizeMake(0, 2);
    self.fromContainer.layer.shadowOpacity = 0.1;
    self.fromContainer.layer.shadowRadius = 4;
    self.fromContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.fromContainer];
    
    UILabel *fromLabel = [[UILabel alloc] init];
    fromLabel.text = @"From";
    fromLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    fromLabel.textColor = [UIColor colorWithRed:0.37 green:0.37 blue:0.37 alpha:1.0];
    fromLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.fromContainer addSubview:fromLabel];
    
    self.fromTextField = [[UITextField alloc] init];
    self.fromTextField.text = @"1";
    self.fromTextField.font = [UIFont systemFontOfSize:18];
    self.fromTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.fromTextField.keyboardType = UIKeyboardTypeDecimalPad;
    [self.fromTextField addTarget:self action:@selector(fromTextFieldChanged) forControlEvents:UIControlEventEditingChanged];
    self.fromTextField.translatesAutoresizingMaskIntoConstraints = NO;
    [self.fromContainer addSubview:self.fromTextField];
    
    self.fromUnitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.fromUnitButton setTitle:@"Meters" forState:UIControlStateNormal];
    self.fromUnitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.fromUnitButton.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
    self.fromUnitButton.layer.cornerRadius = 8;
    self.fromUnitButton.layer.borderWidth = 1;
    self.fromUnitButton.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1.0].CGColor;
    [self.fromUnitButton addTarget:self action:@selector(fromUnitButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.fromUnitButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.fromContainer addSubview:self.fromUnitButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [fromLabel.topAnchor constraintEqualToAnchor:self.fromContainer.topAnchor constant:16],
        [fromLabel.leadingAnchor constraintEqualToAnchor:self.fromContainer.leadingAnchor constant:16],
        
        [self.fromTextField.topAnchor constraintEqualToAnchor:fromLabel.bottomAnchor constant:8],
        [self.fromTextField.leadingAnchor constraintEqualToAnchor:self.fromContainer.leadingAnchor constant:16],
        [self.fromTextField.bottomAnchor constraintEqualToAnchor:self.fromContainer.bottomAnchor constant:-16],
        [self.fromTextField.heightAnchor constraintEqualToConstant:44],
        
        [self.fromUnitButton.topAnchor constraintEqualToAnchor:self.fromTextField.topAnchor],
        [self.fromUnitButton.leadingAnchor constraintEqualToAnchor:self.fromTextField.trailingAnchor constant:12],
        [self.fromUnitButton.trailingAnchor constraintEqualToAnchor:self.fromContainer.trailingAnchor constant:-16],
        [self.fromUnitButton.bottomAnchor constraintEqualToAnchor:self.fromTextField.bottomAnchor],
        [self.fromUnitButton.widthAnchor constraintEqualToConstant:120]
    ]];
}

- (void)setupSwapButton {
    self.swapButton = [UIButton buttonWithType:UIButtonTypeSystem];
    UIImage *swapImage = [UIImage systemImageNamed:@"arrow.up.arrow.down"];
    [self.swapButton setImage:swapImage forState:UIControlStateNormal];
    self.swapButton.tintColor = [UIColor colorWithRed:0.31 green:0.35 blue:0.91 alpha:1.0];
    self.swapButton.backgroundColor = [UIColor colorWithRed:0.31 green:0.35 blue:0.91 alpha:0.1];
    self.swapButton.layer.cornerRadius = 24;
    [self.swapButton addTarget:self action:@selector(swapButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.swapButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.swapButton];
}

- (void)setupToContainer {
    self.toContainer = [[UIView alloc] init];
    self.toContainer.backgroundColor = [UIColor whiteColor];
    self.toContainer.layer.cornerRadius = 12;
    self.toContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    self.toContainer.layer.shadowOffset = CGSizeMake(0, 2);
    self.toContainer.layer.shadowOpacity = 0.1;
    self.toContainer.layer.shadowRadius = 4;
    self.toContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.toContainer];
    
    UILabel *toLabel = [[UILabel alloc] init];
    toLabel.text = @"To";
    toLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    toLabel.textColor = [UIColor colorWithRed:0.37 green:0.37 blue:0.37 alpha:1.0];
    toLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.toContainer addSubview:toLabel];
    
    self.toTextField = [[UITextField alloc] init];
    self.toTextField.text = @"3.28084";
    self.toTextField.font = [UIFont systemFontOfSize:18];
    self.toTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.toTextField.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
    self.toTextField.enabled = NO;
    self.toTextField.translatesAutoresizingMaskIntoConstraints = NO;
    [self.toContainer addSubview:self.toTextField];
    
    self.toUnitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.toUnitButton setTitle:@"Feet" forState:UIControlStateNormal];
    self.toUnitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.toUnitButton.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
    self.toUnitButton.layer.cornerRadius = 8;
    self.toUnitButton.layer.borderWidth = 1;
    self.toUnitButton.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1.0].CGColor;
    [self.toUnitButton addTarget:self action:@selector(toUnitButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.toUnitButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.toContainer addSubview:self.toUnitButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [toLabel.topAnchor constraintEqualToAnchor:self.toContainer.topAnchor constant:16],
        [toLabel.leadingAnchor constraintEqualToAnchor:self.toContainer.leadingAnchor constant:16],
        
        [self.toTextField.topAnchor constraintEqualToAnchor:toLabel.bottomAnchor constant:8],
        [self.toTextField.leadingAnchor constraintEqualToAnchor:self.toContainer.leadingAnchor constant:16],
        [self.toTextField.bottomAnchor constraintEqualToAnchor:self.toContainer.bottomAnchor constant:-16],
        [self.toTextField.heightAnchor constraintEqualToConstant:44],
        
        [self.toUnitButton.topAnchor constraintEqualToAnchor:self.toTextField.topAnchor],
        [self.toUnitButton.leadingAnchor constraintEqualToAnchor:self.toTextField.trailingAnchor constant:12],
        [self.toUnitButton.trailingAnchor constraintEqualToAnchor:self.toContainer.trailingAnchor constant:-16],
        [self.toUnitButton.bottomAnchor constraintEqualToAnchor:self.toTextField.bottomAnchor],
        [self.toUnitButton.widthAnchor constraintEqualToConstant:120]
    ]];
}

- (void)setupQuickConversions {
    self.quickConversionsContainer = [[UIView alloc] init];
    self.quickConversionsContainer.backgroundColor = [UIColor whiteColor];
    self.quickConversionsContainer.layer.cornerRadius = 12;
    self.quickConversionsContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    self.quickConversionsContainer.layer.shadowOffset = CGSizeMake(0, 2);
    self.quickConversionsContainer.layer.shadowOpacity = 0.1;
    self.quickConversionsContainer.layer.shadowRadius = 4;
    self.quickConversionsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.quickConversionsContainer];
    
    self.quickConversionsTitle = [[UILabel alloc] init];
    self.quickConversionsTitle.text = @"Quick Conversions";
    self.quickConversionsTitle.font = [UIFont boldSystemFontOfSize:16];
    self.quickConversionsTitle.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.11 alpha:1.0];
    self.quickConversionsTitle.translatesAutoresizingMaskIntoConstraints = NO;
    [self.quickConversionsContainer addSubview:self.quickConversionsTitle];
    
    self.quickConversionsStack = [[UIStackView alloc] init];
    self.quickConversionsStack.axis = UILayoutConstraintAxisVertical;
    self.quickConversionsStack.spacing = 8;
    self.quickConversionsStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.quickConversionsContainer addSubview:self.quickConversionsStack];
    
    [self updateQuickConversions];
}

- (void)setupConstraints {
    [NSLayoutConstraint activateConstraints:@[
        // Scroll View
        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        // Content View
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
        
        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:60],
        
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:24],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        [self.backButton.heightAnchor constraintEqualToConstant:24],
        
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.backButton.trailingAnchor constant:16],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        
        // Tabs
        [self.tabsContainer.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:24],
        [self.tabsContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:24],
        [self.tabsContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-24],
        
        // From Container
        [self.fromContainer.topAnchor constraintEqualToAnchor:self.tabsContainer.bottomAnchor constant:24],
        [self.fromContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:24],
        [self.fromContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-24],
        
        // Swap Button
        [self.swapButton.topAnchor constraintEqualToAnchor:self.fromContainer.bottomAnchor constant:24],
        [self.swapButton.centerXAnchor constraintEqualToAnchor:self.contentView.centerXAnchor],
        [self.swapButton.widthAnchor constraintEqualToConstant:48],
        [self.swapButton.heightAnchor constraintEqualToConstant:48],
        
        // To Container
        [self.toContainer.topAnchor constraintEqualToAnchor:self.swapButton.bottomAnchor constant:24],
        [self.toContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:24],
        [self.toContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-24],
        
        // Quick Conversions
        [self.quickConversionsContainer.topAnchor constraintEqualToAnchor:self.toContainer.bottomAnchor constant:24],
        [self.quickConversionsContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:24],
        [self.quickConversionsContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-24],
        [self.quickConversionsContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-24],
        
        [self.quickConversionsTitle.topAnchor constraintEqualToAnchor:self.quickConversionsContainer.topAnchor constant:16],
        [self.quickConversionsTitle.leadingAnchor constraintEqualToAnchor:self.quickConversionsContainer.leadingAnchor constant:16],
        
        [self.quickConversionsStack.topAnchor constraintEqualToAnchor:self.quickConversionsTitle.bottomAnchor constant:12],
        [self.quickConversionsStack.leadingAnchor constraintEqualToAnchor:self.quickConversionsContainer.leadingAnchor constant:16],
        [self.quickConversionsStack.trailingAnchor constraintEqualToAnchor:self.quickConversionsContainer.trailingAnchor constant:-16],
        [self.quickConversionsStack.bottomAnchor constraintEqualToAnchor:self.quickConversionsContainer.bottomAnchor constant:-16]
    ]];
}

#pragma mark - Actions

- (void)backButtonTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)categoryButtonTapped:(UIButton *)sender {
    self.selectedCategoryIndex = sender.tag;
    self.fromUnitIndex = 0;
    self.toUnitIndex = 1;
    [self updateCategoryButtons];
    [self updateUnitButtons];
    [self updateConversion];
    [self updateQuickConversions];
}

- (void)fromUnitButtonTapped {
    [self showUnitPickerForType:@"from"];
}

- (void)toUnitButtonTapped {
    [self showUnitPickerForType:@"to"];
}

- (void)swapButtonTapped {
    NSInteger tempIndex = self.fromUnitIndex;
    self.fromUnitIndex = self.toUnitIndex;
    self.toUnitIndex = tempIndex;
    
    NSString *tempText = self.fromTextField.text;
    self.fromTextField.text = self.toTextField.text;
    
    [self updateUnitButtons];
    [self updateConversion];
    [self updateQuickConversions];
}

- (void)fromTextFieldChanged {
    [self updateConversion];
}

#pragma mark - Helper Methods

- (void)updateCategoryButtons {
    for (NSInteger i = 0; i < self.categoryButtons.count; i++) {
        UIButton *button = self.categoryButtons[i];
        if (i == self.selectedCategoryIndex) {
            button.backgroundColor = [UIColor colorWithRed:0.31 green:0.35 blue:0.91 alpha:1.0];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        } else {
            button.backgroundColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1.0];
            [button setTitleColor:[UIColor colorWithRed:0.37 green:0.37 blue:0.37 alpha:1.0] forState:UIControlStateNormal];
        }
    }
}

- (void)updateUnitButtons {
    NSString *category = self.categories[self.selectedCategoryIndex];
    NSArray *units = self.units[category];
    
    [self.fromUnitButton setTitle:units[self.fromUnitIndex] forState:UIControlStateNormal];
    [self.toUnitButton setTitle:units[self.toUnitIndex] forState:UIControlStateNormal];
}

- (void)updateConversion {
    NSString *category = self.categories[self.selectedCategoryIndex];
    NSArray *units = self.units[category];
    NSDictionary *factors = self.conversionFactors[category];
    
    double inputValue = [self.fromTextField.text doubleValue];
    NSString *fromUnit = units[self.fromUnitIndex];
    NSString *toUnit = units[self.toUnitIndex];
    
    double fromFactor = [factors[fromUnit] doubleValue];
    double toFactor = [factors[toUnit] doubleValue];
    
    // 转换到基准单位，再转换到目标单位
    double baseValue = inputValue / fromFactor;
    double result = baseValue * toFactor;
    
    self.toTextField.text = [NSString stringWithFormat:@"%.6g", result];
}

- (void)updateQuickConversions {
    // 清除现有的快速转换
    for (UIView *subview in self.quickConversionsStack.arrangedSubviews) {
        [self.quickConversionsStack removeArrangedSubview:subview];
        [subview removeFromSuperview];
    }
    
    NSString *category = self.categories[self.selectedCategoryIndex];
    NSArray *units = self.units[category];
    NSDictionary *factors = self.conversionFactors[category];
    
    NSString *baseUnit = units[0];
    
    // 添加3个快速转换示例
    for (NSInteger i = 1; i < MIN(4, units.count); i++) {
        NSString *targetUnit = units[i];
        double factor = [factors[targetUnit] doubleValue];
        
        UIView *conversionRow = [[UIView alloc] init];
        
        UILabel *leftLabel = [[UILabel alloc] init];
        leftLabel.text = [NSString stringWithFormat:@"1 %@", baseUnit];
        leftLabel.font = [UIFont systemFontOfSize:14];
        leftLabel.textColor = [UIColor colorWithRed:0.11 green:0.11 blue:0.11 alpha:1.0];
        leftLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [conversionRow addSubview:leftLabel];
        
        UILabel *rightLabel = [[UILabel alloc] init];
        rightLabel.text = [NSString stringWithFormat:@"%.6g %@", factor, targetUnit];
        rightLabel.font = [UIFont systemFontOfSize:14];
        rightLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
        rightLabel.textAlignment = NSTextAlignmentRight;
        rightLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [conversionRow addSubview:rightLabel];
        
        [NSLayoutConstraint activateConstraints:@[
            [leftLabel.leadingAnchor constraintEqualToAnchor:conversionRow.leadingAnchor],
            [leftLabel.centerYAnchor constraintEqualToAnchor:conversionRow.centerYAnchor],
            
            [rightLabel.trailingAnchor constraintEqualToAnchor:conversionRow.trailingAnchor],
            [rightLabel.centerYAnchor constraintEqualToAnchor:conversionRow.centerYAnchor],
            
            [conversionRow.heightAnchor constraintEqualToConstant:24]
        ]];
        
        [self.quickConversionsStack addArrangedSubview:conversionRow];
    }
}

- (void)showUnitPickerForType:(NSString *)type {
    NSString *category = self.categories[self.selectedCategoryIndex];
    NSArray *units = self.units[category];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Select Unit" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSInteger i = 0; i < units.count; i++) {
        NSString *unit = units[i];
        UIAlertAction *action = [UIAlertAction actionWithTitle:unit style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([type isEqualToString:@"from"]) {
                self.fromUnitIndex = i;
            } else {
                self.toUnitIndex = i;
            }
            [self updateUnitButtons];
            [self updateConversion];
            [self updateQuickConversions];
        }];
        [alert addAction:action];
    }
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    
    // iPad support
    if (alert.popoverPresentationController) {
        UIButton *sourceButton = [type isEqualToString:@"from"] ? self.fromUnitButton : self.toUnitButton;
        alert.popoverPresentationController.sourceView = sourceButton;
        alert.popoverPresentationController.sourceRect = sourceButton.bounds;
    }
    
    [self presentViewController:alert animated:YES completion:nil];
}

@end